﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net.Mail;
using System.Net;
using System.Collections;
using LumiSoft.Net.IMAP.Client;
using D.Net.EmailClient;
using D.Net.EmailInterfaces;
using System.Diagnostics;


namespace ACHS_Monitoreo
{
    class Program
    {
        public String ServidorIMAP {get; set;}
        public String ServidorSMTP { get; set; }
        public String UsuarioSMTP { get; set; }
        public String UsuarioIMAP { get; set; }
        public String PasswordSMTP { get; set; }
        public String PasswordIMAP { get; set; }
        public Boolean UsaSSLSMTP { get; set; }
        public Boolean UsaSSLIMAP { get; set; }
        public String EmailSMTP { get; set; }
        public int PuertoIMAP { get; set; }
        public int PuertoSMTP { get; set; }
        public ArrayList ServidoresIMAP;
        public ArrayList ServidoresSMTP;
        public ArrayList UsuariosIMAP;
        public ArrayList PasswordsIMAP;
        public ArrayList ALUsaSSLIMAP;
        public ArrayList PuertosIMAP;
        public ArrayList EmailsIMAP;
        public String DestinoIMAP;

        public Program()
        {
            ServidoresIMAP = new ArrayList();
            ServidoresSMTP = new ArrayList();
            UsuariosIMAP = new ArrayList();
            PasswordsIMAP = new ArrayList();
            ALUsaSSLIMAP = new ArrayList();
            PuertosIMAP = new ArrayList();
            EmailsIMAP = new ArrayList();

            DestinoIMAP = "contacto@maximilianomarin.com";
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.leerParametros();

            String enviado;
            enviado = p.enviarCorreo();

            Boolean recibido;
            recibido = p.leerCorreo(enviado);
        }

        private void leerParametros()
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(@"C:\params.xml");
            XmlNodeList parameters = xdoc.GetElementsByTagName("Parameters");
            XmlNodeList listasender = ((XmlElement)parameters[0]).GetElementsByTagName("MailSender");

            foreach (XmlElement nodo in listasender)
            {
                int i = 0;
                XmlNodeList server = nodo.GetElementsByTagName("server");
                XmlNodeList port = nodo.GetElementsByTagName("port");
                XmlNodeList email = nodo.GetElementsByTagName("email");
                XmlNodeList username = nodo.GetElementsByTagName("userName");
                XmlNodeList password = nodo.GetElementsByTagName("password");
                XmlNodeList enableSSL = nodo.GetElementsByTagName("enableSsl");

                this.ServidorSMTP = server[i].InnerText;
                this.UsuarioSMTP = username[i].InnerText;
                this.PasswordSMTP = password[i].InnerText;
                this.EmailSMTP = email[i].InnerText;
                this.PuertoSMTP = Convert.ToInt32(port[i].InnerText);
                this.UsaSSLSMTP = Convert.ToBoolean(enableSSL[i].InnerText);
                
            }
            
            /*this.ServidorSMTP = "smtp-mail.outlook.com";
            this.UsuarioSMTP = "maximiliano.marin@hotmail.com";
            this.PasswordSMTP = "2154_qaz!!";
            this.EmailSMTP = "contacto@maximilianomarin.com";
            this.PuertoSMTP = 25;
            this.UsaSSLSMTP = true;
             */

            XmlNodeList listareceiver = ((XmlElement)parameters[0]).GetElementsByTagName("MailReceiver");
            foreach (XmlElement nodo in listareceiver)
            {
                int i = 0;
                XmlNodeList server = nodo.GetElementsByTagName("server");
                XmlNodeList port = nodo.GetElementsByTagName("port");
                XmlNodeList email = nodo.GetElementsByTagName("email");
                XmlNodeList username = nodo.GetElementsByTagName("userName");
                XmlNodeList password = nodo.GetElementsByTagName("password");
                XmlNodeList enableSSL = nodo.GetElementsByTagName("enableSsl");

                ServidoresIMAP.Add(server[i].InnerText);
                PuertosIMAP.Add(Convert.ToInt32(port[i].InnerText));
                EmailsIMAP.Add(email[i].InnerText);
                UsuariosIMAP.Add(username[i].InnerText);
                PasswordsIMAP.Add(password[i].InnerText);
                ALUsaSSLIMAP.Add(Convert.ToBoolean(enableSSL[i].InnerText));

            }
            
        }

        private String enviarCorreo()
        {
            
            String cadena = DateTime.Now.ToString();

            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient servidor = new SmtpClient(this.ServidorSMTP);

                mail.From = new MailAddress(this.EmailSMTP);
                mail.To.Add(this.DestinoIMAP);
                mail.Subject = "Probe_"+cadena;
                mail.Body = "Prueba de Envío";

                servidor.Port = PuertoSMTP;
                servidor.Credentials = new NetworkCredential(this.UsuarioSMTP, this.PasswordSMTP);
                servidor.EnableSsl = this.UsaSSLSMTP;
                servidor.Send(mail);

                Console.WriteLine("Correo enviado " + cadena);
                Console.ReadLine();
                 
            }
            catch (SmtpException ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                Console.ReadLine();
            }

            return "Probe_" + cadena;
            
        }

        private Boolean leerCorreo(String asunto)
        {
            Boolean recepcion = false;
            int i = EmailsIMAP.IndexOf(DestinoIMAP);
            String servidor = ServidoresIMAP[i].ToString();
            String usuario = UsuariosIMAP[i].ToString();
            String password = PasswordsIMAP[i].ToString();
            int puerto = Convert.ToInt32(PuertosIMAP[i].ToString());
            Boolean UsaSSL = Convert.ToBoolean(ALUsaSSLIMAP[i].ToString());

            try
            {
                IEmailClient imap = EmailClientFactory.GetClient(EmailClientEnum.IMAP);
                imap.Connect(servidor, usuario, password, puerto, UsaSSL);
                imap.SetCurrentFolder("Inbox");
                imap.LoadRecentMessages(2);
                for (int j = 0; j < 5; j++)
                {
                    IEmail msm = (IEmail)imap.Messages[i];
                    msm.LoadInfos();
                    if (msm.Subject == asunto)
                    {
                        Console.WriteLine("[+]Encontrado!: " + msm.Date.ToString());
                        Console.ReadLine();
                        recepcion = true;
                        break;
                    }    
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error al conectar al servidor IMAP: " + ex.ToString());
                Console.ReadLine();
            }

            return recepcion;
        }
        private void registrarEvento(String nombreLog, String registroLog, String tipoLog, int idLog)
        {
            if (!EventLog.SourceExists(nombreLog))
            {
                EventLog.CreateEventSource(nombreLog, registroLog);
            }

            switch (tipoLog)
            {
                case "Advertencia":
                    EventLog.WriteEntry(nombreLog, registroLog, EventLogEntryType.Warning,idLog);
                    break;
                case "Error":
                    EventLog.WriteEntry(nombreLog, registroLog, EventLogEntryType.Error,idLog);
                    break;
                case "Informacion":
                    EventLog.WriteEntry(nombreLog, registroLog, EventLogEntryType.Information, idLog);
                    break;
            }

        }
    }
}
